package com.taxi.driver.module.order.popup;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.qianxx.utils.DateUtil;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.taxi.driver.R;
import com.taxi.driver.common.BaseFragment;
import com.taxi.driver.config.TypeTripNew;
import com.taxi.driver.event.MapEvent;
import com.taxi.driver.module.amap.AMapFragment;
import com.taxi.driver.module.order.detail.OrderDetailActivity;
import com.taxi.driver.module.order.popup.dagger.DaggerOrderPopupComponent;
import com.taxi.driver.module.order.popup.dagger.OrderPopupModule;
import com.taxi.driver.module.vo.OrderVO;
import com.taxi.driver.util.Navigate;
import com.taxi.driver.util.SpeechUtil;
import com.taxi.driver.widget.ImageViewPlus;
import com.taxi.driver.widget.TextViewPlus;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 功能描述：弹窗
 */
public class OrderPopupFragment extends BaseFragment implements OrderPopupContract.View, SlidingUpPanelLayout.PanelSlideListener {

    public static OrderPopupFragment newInstance(String orderUuid, boolean isAssign) {
        OrderPopupFragment fragment = new OrderPopupFragment();
        Bundle bundle = new Bundle();
        bundle.putString(OrderPopupActivity.KEY_ORDER_UUID, orderUuid);
        bundle.putBoolean(OrderPopupActivity.KEY_ASSIGN, isAssign);
        fragment.setArguments(bundle);
        return fragment;
    }

    @BindView(R.id.sliding)
    SlidingUpPanelLayout mSliding;
    @BindView(R.id.img_background)
    ImageView mImgBackground;
    @BindView(R.id.tv_grab)
    TextView mTvGrab;
    @BindView(R.id.tv_ignore)
    TextView mTvIgnore;
    @BindView(R.id.img_triangle)
    ImageView mImgTriangle;
    @BindView(R.id.layout_map)
    FrameLayout mLayoutMap;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_start)
    TextViewPlus mTvStart;
    @BindView(R.id.tv_start_detail)
    TextView mTvStartDetail;
    @BindView(R.id.tv_end)
    TextViewPlus mTvEnd;
    @BindView(R.id.tv_end_detail)
    TextView mTvEndDetail;
    @BindView(R.id.tv_tag_others)
    TextView mTvTagOthers;
    @BindView(R.id.tv_tag_price)
    TextView mTvTagPrice;
    @BindView(R.id.layout_more)
    LinearLayout mLayoutMore;
    @BindView(R.id.tv_message)
    TextView mTvMessage;
    @BindView(R.id.img_panel)
    ImageViewPlus mImgPanel;
    @BindView(R.id.tv_panel)
    TextView mTvPanel;
    @BindView(R.id.tv_fail)
    TextView mTvFail;
    @BindView(R.id.layout_fail)
    LinearLayout mLayoutFail;
    @BindView(R.id.tv_fail_title)
    TextView mTvFailTitle;
    @BindView(R.id.tv_mile)
    TextView mTvMile;

    @Inject
    OrderPopupPresenter mPresenter;

    private boolean mIsAssign;//忽略订单
    private AMapFragment mAMapFragment;
    private LatLng mCurrentLatLng;
    private OrderVO mVO;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_order_popup, container, false);
        ButterKnife.bind(this, mView);

        mSliding.addPanelSlideListener(this); //设置"展开"或"关闭"的状态监听
        mSliding.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED); //先显示位置信息

        if (mIsAssign) {
            mTvIgnore.setVisibility(View.GONE);
        } else {
            mTvIgnore.setVisibility(View.VISIBLE);
        }
        /* 添加高德地图 */
        if (mAMapFragment == null) {
            FragmentTransaction ft = getChildFragmentManager().beginTransaction();
            ft.add(R.id.layout_map, AMapFragment.newInstance());
            ft.commit();
        }
        return mView;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        DaggerOrderPopupComponent.builder()
                .appComponent(getAppComponent())
                .orderPopupModule(new OrderPopupModule(this))
                .build()
                .inject(this);
        // 设置订单编号
        mIsAssign = getArguments().getBoolean(OrderPopupActivity.KEY_ASSIGN, false);
        mPresenter.setOrderUuid(getArguments().getString(OrderPopupActivity.KEY_ORDER_UUID));
        mPresenter.orderDetail();
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.subscribe();
    }

    @Override
    public void onPause() {
        super.onPause();
        mPresenter.unsubscribe();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPresenter.onDestory();
    }

    @Override
    public void setOrderInfo(OrderVO vo, LatLng latLng) {
        mVO = vo;
        LatLng originLatLng = vo.getOriginLatLng();
        LatLng destLatLng = vo.getDestLatLng();
        mCurrentLatLng = latLng;
        // 显示起点
        mTvStart.setText(vo.originAddress);
        mTvStartDetail.setText(vo.originDetailAddress);
        if (vo.typeTripNew == null || vo.typeTimeNew == null) {
            return;
        }
        // 根据订单行程类型判断
        if (TypeTripNew.isRent(vo.typeTripNew)) {
            mTvEnd.setVisibility(View.GONE);
            mTvEndDetail.setVisibility(View.GONE);
            mTvMile.setVisibility(View.GONE);
            EventBus.getDefault().post(new MapEvent(MapEvent.MAP_CACULATE_ROUTE,
                    mCurrentLatLng, originLatLng, vo.typeTime, mPresenter.driverType()));
        } else {
            mTvEnd.setVisibility(View.VISIBLE);
            mTvEndDetail.setVisibility(View.VISIBLE);
            mTvEnd.setText(vo.destAddress);
            mTvEndDetail.setText(vo.destDetailAddress);
            if (vo.typeTimeNew == 1) {
                mTvMile.setVisibility(View.GONE);
            } else {
                if (Double.parseDouble(vo.planTrip) == 0d) {
                    mTvMile.setVisibility(View.GONE);
                } else {
                    mTvMile.setVisibility(View.VISIBLE);
                    mTvMile.setText(getString(R.string.estimated_mileage, vo.planTrip));
                }
            }
            EventBus.getDefault().post(new MapEvent(MapEvent.MAP_CACULATE_ROUTE,
                    originLatLng, destLatLng, vo.typeTime, mPresenter.driverType()));
        }
        // 根据订单时效类型判断标题显示
        if (vo.typeTripNew == 1 && vo.typeTimeNew == 1) {
            if (mCurrentLatLng == null || originLatLng == null) {
                mTvTitle.setText(R.string.order_popup_title_realtime_unknow);
            } else {
                double distance = AMapUtils.calculateLineDistance(mCurrentLatLng, originLatLng);
                int title = R.string.order_popup_title_realtime_m;
                if (distance > 1000) {
                    distance = distance / 1000; //换算成公里
                    title = R.string.order_popup_title_realtime_km;
                }
                DecimalFormat df = new DecimalFormat("#.##");
                String strDistance = df.format(distance);
                mTvTitle.setText(getString(title, strDistance));
            }
        } else {
            String deparTime = DateUtil.getTodayOrTomorrow(vo.deparTime);
            String timeType = getString(R.string.tag_appintment);
            switch (vo.typeTripNew) {
                case TypeTripNew.DAILY_RENT:
                case TypeTripNew.HALF_DAY_RENT:
                    timeType = getString(R.string.tag_rent);
                    if (!TextUtils.isEmpty(vo.title)) {
                        timeType = vo.title;
                    }
                    break;
                case TypeTripNew.AIRPORT_DROP_OFF:
                    timeType = getString(R.string.tag_airport_drop_off);
                    break;
                case TypeTripNew.AIRPORT_PICKUP:
                    timeType = getString(R.string.tag_airport_pickup);
                    break;
            }
            mTvTitle.setText(String.format("%s | %s", timeType, deparTime));
        }
        // 设置留言和标签
        setServicePriceAndComment(vo);
    }

    private void setServicePriceAndComment(OrderVO vo) {
        String strTip = vo.getStrTip();
        if (TextUtils.isEmpty(strTip)) {
            mLayoutMore.setVisibility(View.GONE);
        } else {
            mLayoutMore.setVisibility(View.VISIBLE);
            mTvTagPrice.setText(getString(R.string.order_popup_service_price, strTip));
        }
        if (TextUtils.isEmpty(vo.remark)) {
            mTvMessage.setVisibility(View.GONE);
        } else {
            mTvMessage.setVisibility(View.VISIBLE);
            mTvMessage.setText(vo.remark);
        }
    }

    @Override
    public void setSlidingExpanded() {
        mImgPanel.setSelected(false); // 改变arrow方向(向上)
        mTvPanel.setText(R.string.order_popup_slide_up); // 改变文字提示
    }

    @Override
    public void setSlidingCollapsed() {
        mImgPanel.setSelected(true); // 改变arrow方向(向下)
        mTvPanel.setText(R.string.order_popup_slide_down); // 改变文字提示
    }

    @Override
    public void grabSuccess(String orderUuid) {
        Navigate.openOrderOngoing(getContext(), orderUuid); //跳转到进行中订单页
        getActivity().finish(); //关闭界面
    }

    @Override
    public void grabFail(int time, String title, String reason) {
        mTvGrab.setBackground(getResources().getDrawable(R.drawable.sel_grap_failed));
        mTvGrab.setEnabled(false);
        mTvGrab.setText("关闭\n" + String.valueOf(time));
        mTvFailTitle.setEnabled(false);
        mTvFailTitle.setText(title);
        mTvFail.setText(reason);
        mImgTriangle.setSelected(true); //显示深色三角号
        mLayoutFail.setVisibility(View.VISIBLE);
        mTvIgnore.setVisibility(View.GONE);
    }

    @Override
    public void orderInvalid(int time, String reason) {
        mTvGrab.setBackground(getResources().getDrawable(R.drawable.sel_grap_failed));
        mTvGrab.setEnabled(false);
        mTvGrab.setText("关闭\n" + String.valueOf(time));
        mTvFailTitle.setEnabled(false);
        mTvFailTitle.setText("订单失效");
        mTvFail.setText(reason);
        mImgTriangle.setSelected(true); //显示深色三角号
        mLayoutFail.setVisibility(View.VISIBLE);
        mTvIgnore.setVisibility(View.GONE);
    }

    @Override
    public void showBuffering(int time, int bufferStatus) {
        mTvGrab.setEnabled(bufferStatus == 1);
        switch (bufferStatus) {
            case 0:
                mTvGrab.setText(String.valueOf(time));
                break;
            case 1:
                if (mIsAssign) {
                    mTvGrab.setText("收到派单\n" + time);
                } else {
                    mTvGrab.setText("抢单\n" + time);
                }
                break;
            default:
                mTvGrab.setText("关闭\n" + String.valueOf(time));
                break;
        }
    }

    @Override
    public void closeActivity() {
        getActivity().finish();
    }

    @Override
    public void hideIgnore() {
        mTvIgnore.setVisibility(View.GONE);
    }

    @Override
    public void setAssign() {
        mIsAssign = true;
        mTvIgnore.setVisibility(View.GONE);
    }

    /**
     * 监听mSliding的展开或关闭
     *
     * @param panel
     * @param previousState
     * @param newState
     */
    @Override
    public void onPanelStateChanged(View panel, SlidingUpPanelLayout.PanelState previousState, SlidingUpPanelLayout.PanelState newState) {
        switch (newState) {
            case EXPANDED: // laySliding已展开，显示地址信息
                setSlidingExpanded();
                break;
            case COLLAPSED: // laySliding已收起，显示地图
                setSlidingCollapsed();
                break;
        }
    }

    @Override
    public void onPanelSlide(View panel, float slideOffset) {

    }

    @Override
    public void onAttachFragment(Fragment childFragment) {
        super.onAttachFragment(childFragment);
        if (childFragment instanceof AMapFragment) {
            mAMapFragment = (AMapFragment) childFragment;
        }
    }

    @OnClick({R.id.tv_grab, R.id.img_close, R.id.iv_location, R.id.tv_ignore})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_grab:
                if (mVO.typeInteractive == 2) {
                    mPresenter.grabOrder();
                } else {
//                    Navigate.openOrderOngoing(getContext(), mPresenter.getOrderUuid());
                    OrderDetailActivity.start(getActivity(),  mPresenter.getOrderUuid(),110);
                    getActivity().finish();
                }
                break;
            case R.id.img_close: //关闭界面
                SpeechUtil.stop(getContext());
                getActivity().finish();
                break;
            case R.id.iv_location: //重置规划路径
                LatLng origin, dest;
                if (TypeTripNew.isRent(mVO.typeTimeNew)) {//即时单,日租/半日租
                    origin = mCurrentLatLng;
                    dest = mVO.getOriginLatLng();
                } else {
                    origin = mVO.getOriginLatLng();
                    dest = mVO.getDestLatLng();
                }
                EventBus.getDefault().post(new MapEvent(MapEvent.MAP_LOCATION, origin, dest));
                break;
            case R.id.tv_ignore:
                mPresenter.ignoringOrder();
                SpeechUtil.stop(getContext());
                getActivity().finish();
                break;
        }
    }
}
